#include<iostream>
#include<vector>
#include<list>
#include<tuple>
#include<unordered_map>
#include<unordered_set>
using namespace std;

struct TupleHash {
    size_t operator()(const tuple<int, int, int>& t) const {
        auto [a, b, c] = t;
        return ((size_t)a * 1315423911u) ^ ((size_t)b * 2654435761u) ^ ((size_t)c * 97531u);
    }
};

class Router {
public:
    Router(int memoryLimit) {
        _memoLimit = memoryLimit;
    }

    bool addPacket(int source, int destination, int timestamp) {
        auto tup = make_tuple(source, destination, timestamp);
        if (use.count(tup)) return false;
        if ((int)lt.size() >= _memoLimit) {
            use.erase(lt.front());
            lt.pop_front();
        }
        lt.push_back(tup);
        use.insert(tup);
        return true;
    }

    vector<int> forwardPacket() {
        if (lt.empty()) return {};
        auto tup = lt.front();
        lt.pop_front();
        use.erase(tup);
        return { get<0>(tup), get<1>(tup), get<2>(tup) };
    }

    int getCount(int destination, int startTime, int endTime) {
        int gcount = 0;
        for (auto& tup : lt) {
            if (get<1>(tup) == destination && get<2>(tup) >= startTime && get<2>(tup) <= endTime) {
                gcount++;
            }
        }
        return gcount;
    }

private:
    int _memoLimit;
    list<tuple<int, int, int>> lt;
    unordered_set<tuple<int, int, int>, TupleHash> use;
};
